package com.liyuan.help_e.controller;

import com.liyuan.help_e.model.UploadFileResultJson;
import com.liyuan.help_e.model.User;
import com.liyuan.help_e.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadFileController {
    @Autowired
    UserService userService;
    @RequestMapping("/file/upload")
    public UploadFileResultJson upload(HttpServletRequest request) throws IOException {
        String newFileName = restoreFile("editormd-image-file",request);
        return new UploadFileResultJson(1, "upload resource success!", "/images/img/" + newFileName);
    }
    @PostMapping("/file/uploadImage")
    public void uploadImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String newFileName = restoreFile("imageFile",request);
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        userService.updateUserAvatarUrl(username,"/images/img/" + newFileName);
        response.sendRedirect("/personal.html");
    }

    private String restoreFile(String uploadFilename,HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest request_ = (MultipartHttpServletRequest) request;
        MultipartFile file = request_.getFile(uploadFilename);
        String newFileName=null;
        if (file != null) {
            String[] fileTypes = file.getContentType().split("/");
            String fileType = fileTypes[fileTypes.length - 1];
            String path = System.getProperty("user.dir") + "\\target\\classes\\static\\images\\img\\";
            newFileName = UUID.randomUUID().toString() + "." + fileType;
            File file1 = new File(path + newFileName);
            file.transferTo(file1);
        }
        return newFileName;
    }
}
